﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Core.DataAccess.Model.Project.Entrepot;
using Core.Framework.Model.Common;
using Core.Framework.Util;
using Core.IBusiness.IEntrepotModule;
using Core.IBusiness.IEntrepotModule.Model;

namespace Core.Business.EntrepotModule
{
    public class EntrepotOperation : IEntrepotOperation
    {
        public MethodResult<List<ProductAttrbute>> GetAttributes(string projectToken, List<EntrepotAttributeEnum> attributes, Pagination pagination)
        {
            try
            {
                if (attributes ==null || attributes?.Count < 1)
                {
                    return new MethodResult<List<ProductAttrbute>> { IsFinished = false, Discription = "attributes is null" };
                }

                using (var context = new ProjectEntrepotContext())
                {

                    var query = context
                                    .ProductAttrbute
                                    .Where(a => a.ProjectToken == projectToken && attributes.Select(b => (int)b).Contains(a.Type))
                                    .Pagination(pagination);

                    return new MethodResult<List<ProductAttrbute>> { IsFinished = true, Date = query };

                }
            }
            catch (Exception e)
            {
                return new MethodResult<List<ProductAttrbute>> { IsFinished = false, Discription = e.Message };
            }
        }

        public MethodResult<ProductCardBuiderResult> GetProductCardContent(string projectToken)
        {
            ProductCardBuiderModel buiderModel = new ProductCardBuiderModel {
                CardInfos = new List<ProductCardInfo>()
            };

            using (var context = new ProjectEntrepotContext())
            {
                // 获取所有商品模板
                var sources = context
                    .ProductTemplate
                    .Where(a => a.ProjectToken == projectToken)
                    .ToList();

                if (sources.Count > 0)
                {
                    var temps = sources.Select(a => a.Id);

                    // 获取所有库存信息
                    var skus =
                        context
                            .ProductSku
                            .Where(a => temps.Contains(a.TemplateKey))
                            .ToList();

                    // 商品库存处理
                    if (sources?.Count > 0 && skus?.Count > 0)
                        foreach (var temp in sources)
                            temp.ProductSkus = skus.Where(a => a.TemplateKey == temp.Id).ToList();

                    var result = new ProductCardBuiderResult
                    {
                        Title = "老布匠",
                        CardInfos = new List<object>()
                    };

                    foreach (var item in sources)
                    {
                        Thread.Sleep(10);

                        var jObject = item.Content.TryToJObject();

                        // 图片路径
                        var imgsrc = jObject["imgs"][0].ToString();
                        imgsrc = imgsrc.IndexOf("http") > -1 ? imgsrc : "https://file.help-itool.com" + imgsrc;

                        // 小标题
                        var subtitle = jObject["subtitle"].ToString();

                        // 小程序码

                        // 产品规格
                        var specifications = new Dictionary<string, string>();
                        foreach (var sku in item.ProductSkus)
                        {
                            if (sku.IsWholesale == true || sku.SalesConfirm == true)
                            {
                                if (sku.Content.IndexOf("pecification") > -1)
                                {
                                    var jSKUObject = sku.Content.TryToJObject();
                                    specifications.Add(
                                        jSKUObject?["Specification"]?.ToString(),
                                        $"￥{decimal.Round((decimal)sku.SalesPrice, 2).ToString()}");
                                }
                                else
                                {
                                    if (specifications.ContainsKey("标准"))
                                    {
                                        specifications.Add(
                                        $"标准-{specifications.Count}",
                                        $"￥{decimal.Round((decimal)sku.SalesPrice, 2).ToString()}");
                                    }
                                    else
                                    {
                                        specifications.Add(
                                        "标准",
                                        $"￥{decimal.Round((decimal)sku.SalesPrice, 2).ToString()}");
                                    }
                                    
                                }
                            }
                        }


                        buiderModel.CardInfos.Add(new ProductCardInfo { 
                            PreviewImg = imgsrc,
                            QRPath = $"https://file.help-itool.com/Content/Product/hsrs/product-{item.Id}.png",
                            Specifications = specifications,
                            SubTitle = subtitle,
                            Title = item.Title
                        });
                    }

                    foreach (var card in buiderModel.CardInfos)
                    {
                        List<object> data = new List<object>();

                        // 背景
                        data.Add(new
                        {
                            type = "image",
                            url = "https://itool.store/images/goods_poster.png",
                            top = 0,
                            left = 0,
                            width = 680,
                            height = 1060
                        });

                        // 商品主图
                        data.Add(new
                        {
                            type = "image",
                            url = card.PreviewImg,
                            top = 42,
                            left = 42,
                            width = 600,
                            height = 500
                        });

                        // 主标题
                        data.Add(new
                        {
                            type = "text",
                            content = card.Title,
                            fontSize = 30,
                            lineHeight = 38,
                            color = "#000",
                            textAlign = "left",
                            top = 584,
                            left = 44,
                            width = 400,
                            MaxLineNumber = 2,
                            breakWord = true,
                            bolder = true // 加粗
                        });

                        // 小标题
                        data.Add(new
                        {
                            type = "text",
                            content = card.SubTitle,
                            fontSize = 24,
                            lineHeight = 38,
                            color = "#827f7f",
                            textAlign = "left",
                            top = 630,
                            left = 44,
                            width = 400,
                            MaxLineNumber = 2,
                            breakWord = true
                        });

                        int keyValueIndex = 1;

                        // 价格 - 规格
                        foreach (var keyValuePair in card.Specifications)
                        {
                            // lable
                            data.Add(new
                            {
                                type = "text",
                                content = keyValuePair.Key,
                                fontSize = 24,
                                color = "#3e3e3e",
                                textAlign = "left",
                                top = 640 + (keyValueIndex * 50),
                                left = 44.5
                            });

                            // price
                            data.Add(new
                            {
                                type = "text",
                                content = keyValuePair.Value,
                                fontSize = 25,
                                color = "#E62004",
                                textAlign = "left",
                                top = 640 + (keyValueIndex * 50),
                                left = 200
                            });

                            if (keyValueIndex < card.Specifications.Count)
                            {
                                // line
                                data.Add(new
                                {
                                    type = "text",
                                    content = "                                ",
                                    fontSize = 24,
                                    color = "#c7c7c7",
                                    textAlign = "left",
                                    top = 640 + (keyValueIndex * 50),
                                    left = 44,
                                    bolder = true,
                                    textDecoration = "underline"
                                });
                            }

                            keyValueIndex++;

                        }


                        // 更多商品详情
                        data.Add(new
                        {
                            type = "text",
                            content = "更多商品详情",
                            fontSize = 24,
                            color = "#827f7f",
                            textAlign = "left",
                            top = 850,
                            left = 475,
                            lineHeight = 20,
                            MaxLineNumber = 2,
                            breakWord = true,
                            width = 580
                        });

                        // 二维码
                        data.Add(new
                        {
                            type = "image",
                            url = card.QRPath,
                            top = 620,
                            left = 450,
                            width = 200,
                            height = 200
                        });

                        // 底部
                        data.Add(new
                        {
                            type = "text",
                            content = result.Title,
                            fontSize = 24,
                            color = "#dadada",
                            textAlign = "left",
                            top = 920,
                            left = 300,
                            lineHeight = 20,
                            MaxLineNumber = 2,
                            breakWord = true,
                            width = 580,
                            textDecoration = "underline"
                        });

                        result.CardInfos.Add(data);
                    }


                    skus = null;

                    return new MethodResult<ProductCardBuiderResult>
                    {
                        Date = result,
                        IsFinished = true
                    };


                }

                return new MethodResult<ProductCardBuiderResult>();

            }
        }

        public MethodResult<List<ProductTemplate>> GetTemplateByAttributes(string projectToken, List<EntrepotAttributeEnum> attributes, Pagination pagination, string search = null)
        {
            try
            {
                if (attributes?.Count < 1)
                {
                    return new MethodResult<List<ProductTemplate>>{ IsFinished = false, Discription = "attributes is null" };
                }

                using (var context = new ProjectEntrepotContext())
                {
                    var query = context
                                    .ProductAttrbute
                                    .Where(a => a.ProjectToken == projectToken && attributes.Select(b => (int)b).Contains(a.Type))
                                    .Pagination(pagination);

                    if (query?.Count > 0)
                    {
                        var temps = context
                            .ProductTemplate
                            .Where(a => query.Select(b => b.ProductId).Contains(a.Id))
                            .ToList();

                        
                        var skus = context
                                .ProductSku
                                .Where(a => temps.Select(b => b.Id).Contains(a.TemplateKey))
                                .ToList();

                        foreach (var item in temps)
                        {
                            item.ProductAttrbutes = query.Where(a => a.ProductId == item.Id).ToList();
                            item.ProductSkus = skus.Where(a => a.TemplateKey == item.Id).ToList();
                        }

                        return new MethodResult<List<ProductTemplate>> { IsFinished = true, Date = temps };

                    }
                    else
                    {
                        return new MethodResult<List<ProductTemplate>> { IsFinished = true, Date = null };

                    }

                }
            }
            catch (Exception e)
            {
                return new MethodResult<List<ProductTemplate>>{ IsFinished = false, Discription = e.Message};
            }
        }

        public MethodResult<int> OperationAttrbute(ProductAttrbute model, SqlExecType sqlExecType)
        {
            return Utils.SqlExecType<ProjectEntrepotContext, ProductAttrbute>(model,
                sqlExecType,
                a => a.Id == model.Id);
        }
    }
}
